package com.android.kmlmrg.views;

import java.util.List;

import android.app.ActionBar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.kmlmrg.R;
import com.android.kmlmrg.R.menu;
import com.android.kmlmrg.dao.AddressDao;
import com.android.kmlmrg.event.RestUpdateUserEvent;
import com.android.kmlmrg.event.RestUpdateUserPhotoEvent;
import com.android.kmlmrg.event.UserDelEvent;
import com.android.kmlmrg.event.UserFieldChangedEvent;
import com.android.kmlmrg.listener.custom.RestUpdateUserListener;
import com.android.kmlmrg.listener.custom.RestUpdateUserPhotoListener;
import com.android.kmlmrg.listener.custom.RestUserDelListener;
import com.android.kmlmrg.listener.custom.UserFieldListener;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.ServiceController;
import com.android.kmlmrg.services.rest.method.DeleteUser;
import com.android.kmlmrg.services.rest.method.UpdateUser;
import com.android.kmlmrg.services.rest.method.UpdateUserPhoto;
import com.android.kmlmrg.utils.Const;
import com.android.kmlmrg.utils.MenuBarHelper;
import com.android.kmlmrg.utils.MyItemizedOverlay;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;


public class ViewContact extends MapActivity implements Const, RestUpdateUserPhotoListener, UserFieldListener, RestUpdateUserListener,RestUserDelListener {


	/**LOG**/
	private static final  String LOG_TAG = ViewContact.class.getName();

	private static final int PICK_IMAGE_REQUEST_CODE = 0002022020;

	private ServiceController serviceController;

	private  MapView mapView;
	
	private MyLocationOverlay myLocationOverlay;

	private List<Overlay> overlays ;

	private MyItemizedOverlay myItemizedOverlay;

	private AddressDao addressDao = new AddressDao();
	
	private User user;
	
	private ImageView badge ;

	private  Dialog progress;
	/****/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i(LOG_TAG, "START - onCreate");
		super.onCreate(savedInstanceState);
		DeleteUser.addListener(this);
		UpdateUserPhoto.addListener(this);
		User.addListener(this);
		UpdateUser.addListener(this);
		setContentView(R.layout.view_contact);  
		
		Log.i(LOG_TAG, "END - onCreate");

	}
	
	@Override
	protected void onResume() {
		Log.i(LOG_TAG, "START - onResume");
		initialized();
		Log.i(LOG_TAG, "END - onResume");
		super.onResume();
	}

	
	@Override
	protected void onPause() {
		Log.i(LOG_TAG, "START - onPause");
//		serviceController = null;
//		mapView = null;
//		user = null;		
		Log.i(LOG_TAG, "END - onPause");
		super.onPause();		
	}


	@Override
	public boolean onCreateOptionsMenu(Menu pMenu) {
		Log.i(LOG_TAG, "START - onCreateOptionsMenu(Menu pMenu)");
		getMenuInflater().inflate (menu.view_contact, pMenu);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			ActionBar actionBar = getActionBar();
			actionBar.setDisplayHomeAsUpEnabled(true);
		}

		Log.i(LOG_TAG, "END - onCreateOptionsMenu(Menu pMenu)");
		return super.onCreateOptionsMenu(pMenu);

	}


	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i(LOG_TAG, "START - onOptionsItemSelected");
		Log.i(LOG_TAG, "END - onOptionsItemSelected");
		return MenuBarHelper.manageMenuItemClick(item, this);

	}

	public User getUser() {
		return user;
	}

	private void populateView(User user){
		Log.i(LOG_TAG, "START - populateView(User user)");
		 badge = (ImageView)findViewById(R.id.quickContactBadge1);
		TextView nom = (TextView) findViewById(R.id.viewContactName);
		TextView prenom = (TextView) findViewById(R.id.viewContactLastName);
		TextView tel = (TextView) findViewById(R.id.viewContactNumber);
		TextView email = (TextView) findViewById(R.id.viewContactEmail);
		TextView birth = (TextView) findViewById(R.id.viewContactBirthday);

		nom.setText(user.getNom());
		prenom.setText(user.getPrenom());
		tel.setText(user.getTel());
		email.setText(user.getEmail());
		birth.setText(user.getDateNaissance());

		if (user.getPathExternalStorage()== null ) {
			badge.setImageResource(R.drawable.contact);
		}else {
			 Bitmap bitmap =  BitmapFactory.decodeFile(user.getPathExternalStorage());
			badge.setImageBitmap(bitmap);
		}

		Log.i(LOG_TAG, "END - populateView(User user)");
	}
	
	
	
	
	
	



	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i(LOG_TAG, "START - onActivityResult");
		initialized();
		if(requestCode == PICK_IMAGE_REQUEST_CODE && data != null && data.getData() != null){
			Uri uri = data.getData();
			if (uri != null) {

				Cursor cursor = getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
				cursor.moveToFirst();

				final String imageFilePath = cursor.getString(0);
				Log.i(LOG_TAG, "imageFilePath : " + imageFilePath );
				serviceController.updateUserPhoto(user, imageFilePath);
				cursor.close();
				progress =ProgressDialog.show(ViewContact.this, 
		                "Loading data", "Please wait...");
			}
		}else if(requestCode == REQUEST_UPDATE_PROFIL_CODE && data != null && data.getExtras() != null){
			if(resultCode == RESULT_OK){
				User vUser = (User)data.getSerializableExtra("user"); 
				ServiceController.getInstance().updateUserServ(vUser);
				progress =ProgressDialog.show(ViewContact.this, 
		                "Loading data", "Please wait...");
				Log.i(LOG_TAG,"*update User : " + user.getNom());
			}
		}
		Log.i(LOG_TAG, "END - onActivityResult");

	}


	public void lauchPikerImage () {
		Log.i(LOG_TAG, "START - lauchPikerImage");
		Intent vIntent =  new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(vIntent, PICK_IMAGE_REQUEST_CODE);
		Log.i(LOG_TAG, "END - lauchPikerImage");
	}

	public void launchEditProfil(){
		Log.i(LOG_TAG, "START - launchEditProfil");
		Intent vIntent =  new Intent(this, AddOrUpdateContact.class);
		vIntent.putExtra("user",user);
		vIntent.putExtra("isForAdd", false);
		startActivityForResult(vIntent, REQUEST_UPDATE_PROFIL_CODE);
		Log.i(LOG_TAG, "END - launchEditProfil");
	}

	public void launchDeleteProfil(){
		Log.i(LOG_TAG, "START - launchDeleteProfil");
		serviceController.deleteUser(this.getUser());
		Log.i(LOG_TAG, "END - launchDeleteProfil");
	}

	public void resultUpdateUserPhotoRequest(RestUpdateUserPhotoEvent event) {
		Log.i(LOG_TAG, "START - resultUpdateUserRequest");
		RelativeLayout vRelativeLayout = (RelativeLayout) findViewById(R.id.layoutViewContact);
		vRelativeLayout.refreshDrawableState();
		vRelativeLayout.invalidate();
		if (progress != null){
			progress.dismiss();
		}
		Log.i(LOG_TAG, "END - resultUpdateUserRequest");

	}

	public void userFielChanged(UserFieldChangedEvent event) {
		Log.i(LOG_TAG, "START - userFielChanged");
	 user = (User) event.getSource();
	 populateView(user);
	 RelativeLayout vRelativeLayout = (RelativeLayout) findViewById(R.id.layoutViewContact);
	 Bitmap bitmap =  BitmapFactory.decodeFile(user.getPathExternalStorage());
	 
	 badge.setImageBitmap(bitmap);
		vRelativeLayout.refreshDrawableState();
		vRelativeLayout.invalidate();
		if (progress != null){
			progress.dismiss();
		}
		Log.i(LOG_TAG, "END - userFielChanged");
		
	}
	
	private void initialized () {
		Log.i(LOG_TAG, "START - initialized");
		serviceController = ServiceController.getInstance();
		mapView = (MapView) findViewById(R.id.contact_mapview);
		mapView.setBuiltInZoomControls(false);
		mapView.setClickable(false);
		overlays = mapView.getOverlays();	
		Drawable drawable = getResources().getDrawable(R.raw.map_pin_24);
		myItemizedOverlay = new MyItemizedOverlay(drawable , this);
		overlays.add(myItemizedOverlay);
		user = (User) getIntent().getSerializableExtra("viewContact");
		populateView(user);
		addMakerContactUndermaps (user);
		mapView.invalidate();
		Log.i(LOG_TAG, "END - initialized");
	}
	
	private void addMakerContactUndermaps ( User pUser ) {
		Log.i(LOG_TAG, "START - addMakerContactUndermaps");	
		if (pUser.getNomRue()==null && pUser.getNumeroRue()==null && pUser.getPays()==null && pUser.getVille()==null) {
			Log.i(LOG_TAG, "ERROR : L adresse est incomplete " );	
			Log.i(LOG_TAG, "END - addMakerContactUndermaps");	
			return ;
		}		
		String vSearchAddress = new StringBuilder()
		.append( pUser.getNumeroRue() ).append(" ")
		.append(pUser.getNomRue() ).append(" ")
		.append(pUser.getVille() ).append(" ")
		.append(pUser.getCodePostal()).append(" ")
		.append(pUser.getPays()).toString();
		Log.i(LOG_TAG, "ADDRESS : " + vSearchAddress );	

		Address vAddress = addressDao.getLatitudeAndLongitudeFromGoogleMapForAddress(this, vSearchAddress);
		if (vAddress ==null ){
			return ;
	}
	

		Double vLatitude = Double.valueOf( vAddress.getLatitude() * 1E6 );
		Double vLongitude = Double.valueOf(vAddress.getLongitude() * 1E6 );
		GeoPoint vGeoPoint = new GeoPoint(vLatitude.intValue(), vLongitude.intValue());
		
		myItemizedOverlay.addItem(vGeoPoint, pUser.getNom(), pUser.getNom() );
		mapView.getController().animateTo(vGeoPoint);
		mapView.getController().setZoom(17);
		Log.i(LOG_TAG, "END - addMakerContactUndermaps");	
	}
	public void resultGetUserRequest(RestUpdateUserEvent event) {
		Log.i(LOG_TAG, "START - resultGetUserRequest");
		
	
		if (event.isUpdate()) {
			user = event.getUser();
			 populateView(user);
			 RelativeLayout vRelativeLayout = (RelativeLayout) findViewById(R.id.layoutViewContact);
			vRelativeLayout.refreshDrawableState();
			vRelativeLayout.invalidate();
		}

		if (progress != null){
			progress.dismiss();
		}
		Log.i(LOG_TAG, "END - resultGetUserRequest");
	}

	public void resultUserDelRequest(UserDelEvent event) {
		Log.i(LOG_TAG, "START - resultUserDelRequest");
		serviceController.getUsers().delUser(user);
		this.finish();
		Log.i(LOG_TAG, "END - resultUserDelRequest");
	}

}
